<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import Portservice from "@/apis";
import type Typings from "@/typings";
import { $confirm, $singleMsg } from "xt-public/plugins/utils/element.ts";
import { jobCategory, levelDict, sfMap } from "@/constant";
import { getTimeFromDate } from "@/utils";
import jobDrawer from "./components/drawer.vue";
import todoBatchDialog from "@/components/global/todoBatchDialog.vue";

// 批量操作弹窗
const batchDialog = ref();
const batchController = {
  open(rows: Typings.Job.job[]) {
    batchDialog.value.open(rows);
  },
};

// 抽屉
const drawer = ref();
const drawerController = {
  open(scope: Typings.Job.scope | null, type: string = "check") {
    drawer.value.open(scope, type);
  },

  async confirm() {
    tableRef.value.getInstance().clearSelection();
    await tableController.getList();
    tableRef.value.getInstance().doLayout();
  },
};

// 项目信息
const projectList = ref([]);
const projectController = {
  async getProjectList() {
    const { data } = await Portservice.projectListApi();
    projectList.value = data;
  },
};

// 搜索栏数据
const searchForm = ref<Partial<Typings.Job.job>>({
  title: "",
  level: "",
  category: "",
  projectCode: [],
  isFinish: false,
});

// 搜索栏 formJson
const searchFormJson = computed<Typings.XtPublic.SearchBar.formJson[]>(() => {
  return [
    {
      el: "input",
      span: 8,
      prop: "title",
      label: "标题",
    },

    {
      el: "date-picker",
      span: 8,
      prop: "createdTime",
      label: "创建时间",
      type: "daterange",
      format: "YYYY-MM-DD",
    },

    {
      el: "select",
      span: 8,
      prop: "level",
      label: "重要程度",
      options: levelDict,
    },

    {
      el: "select",
      span: 8,
      prop: "category",
      label: "分类",
      options: jobCategory,
    },

    {
      isHide: () => {
        const isHide = searchForm.value.category !== "1";
        if (isHide) {
          searchForm.value.projectCode = [];
        }
        return isHide;
      },
      el: "cascader",
      span: 8,
      prop: "projectCode",
      label: "项目",
      placeholder: "请选择项目",
      options: projectList.value,
    },

    {
      el: "select",
      span: 8,
      prop: "isFinish",
      label: "是否完成",
      options: sfMap,
    },
  ];
});

// 搜索栏控制器
const searchController = {
  search() {
    tableController.getList();
  },

  reset() {
    tableController.getList();
  },
};

// 表格 columns 数据
const tableColumns = computed<Typings.XtPublic.Table.column<Typings.Job.job>[]>(
  () => {
    return [
      {
        isHide: () => {
          const isHide = searchForm.value.category !== "1";
          return isHide;
        },
        prop: "projectName",
        label: "项目",
        minWidth: 200,
      },

      {
        prop: "title",
        label: "标题",
        minWidth: 300,
        clickFn: (scope) => {
          drawerController.open(scope, "check");
        },
      },
      {
        colType: "tag",
        prop: "level",
        label: "紧急程度",
        minWidth: 100,
        options: levelDict,
      },
      {
        colType: "tag",
        prop: "isFinish",
        label: "是否完成",
        minWidth: 100,
        options: sfMap,
      },
      {
        colType: "tag",
        prop: "category",
        label: "类别",
        minWidth: 100,
        options: jobCategory,
      },
      {
        prop: "createdTime",
        label: "创建时间",
        colType: "time",
        minWidth: 180,
        format: "YYYY-MM-DD HH:mm:ss",
      },
    ];
  }
);

const tableRef = ref();

// 表格数据
const table = ref<Typings.Job.table>({
  data: [],
  loading: false,
  pagination: {
    page: 1,
    size: 10,
    total: 0,
  },
  batchData: [],
});

// 表格控制器
const tableController = {
  // 获取工作待办列表数据
  async getList() {
    try {
      table.value.loading = true;
      const { createdTime, projectCode, ...lastParams } = searchForm.value;
      const params: Typings.Common.plainObj = {
        page: table.value.pagination.page,
        size: table.value.pagination.size,
        projectCode: projectCode?.join(","),
        ...lastParams,
      };

      if (createdTime?.length) {
        params["startTime"] = getTimeFromDate(createdTime[0], "start");
        params["endTime"] = getTimeFromDate(createdTime[1], "end");
      }

      const { data } = await Portservice.jobListApi(params);
      table.value.data = data.list || [];
      table.value.pagination.total = data.total || 0;
    } finally {
      table.value.loading = false;
    }
  },
  // 分页器变化
  paginationChange() {
    tableController.getList();
  },
  // 新增
  create() {
    drawerController.open(null, "create");
  },
  // 更新
  update(scope: Typings.Job.scope) {
    drawerController.open(scope, "update");
  },
  // 删除
  async delete(scope: Typings.Job.scope) {
    await $confirm({
      tip: "确定要删除该工作待办吗？",
    });

    await Portservice.jobRemoveApi({ id: scope.row.id });

    $singleMsg({
      message: "删除成功",
    });

    tableController.getList();
  },
  // 切换转完成/转待办
  async setFinish(scope: Typings.Job.scope, isFinish: boolean) {
    await $confirm({
      tip: `确定要将该工作待办数据${isFinish ? "转完成" : "转待办"}吗？`,
    });

    await Portservice.jobFinishApi({ id: scope.row.id, isFinish });

    $singleMsg({
      message: `${isFinish ? "转完成" : "转待办"}操作成功`,
    });

    tableController.getList();
  },
  // 切换置顶/取消置顶
  async setTop(scope: Typings.Job.scope, isTop: boolean) {
    await $confirm({
      tip: `确定要${isTop ? "" : "取消"}置顶工作待办吗？`,
    });

    await Portservice.jobSetTopApi({ id: scope.row.id, isTop });

    $singleMsg({
      message: `${isTop ? "" : "取消"}置顶成功`,
    });

    tableController.getList();
  },
  // 设置表格每行的样式
  setRowClass(scope: Typings.Job.scope) {
    if (scope.row.isTop) return "is-set-top";
  },
  // 多选
  handleSelectionChange(rows: Typings.Job.job[]) {
    table.value.batchData = rows;
  },
  // 批量操作
  batch() {
    batchController.open(table.value.batchData);
  },
};

onMounted(() => {
  projectController.getProjectList();
  tableController.getList();
});
</script>

<template>
  <div class="page-container w-full h-full overflow-hidden flex flex-col">
    <div class="search-container">
      <xt-search-bar
        :data="searchForm"
        :formJson="searchFormJson"
        @search="searchController.search"
        @reset="searchController.reset"
      >
        <template #btn>
          <xt-link type="success" @click="tableController.create">新增</xt-link>
          <xt-link @click="tableController.batch" v-if="table.batchData.length"
            >批量操作</xt-link
          >
        </template>
      </xt-search-bar>
    </div>
    <div class="table-container height-0 flex-1 overflow-hidden">
      <xt-table
        ref="tableRef"
        height="100%"
        showSelection
        v-loading="table.loading"
        :data="table.data"
        :columns="tableColumns"
        :row-class-name="tableController.setRowClass"
        @selection-change="tableController.handleSelectionChange"
      >
        <template #operate>
          <xt-table-column label="操作" align="center" width="240">
            <template #default="scope">
              <xt-link class="mr-[8px]" @click="tableController.update(scope)"
                >编辑</xt-link
              >
              <xt-link
                class="mr-[8px]"
                type="danger"
                @click="tableController.delete(scope)"
                >删除</xt-link
              >
              <xt-link
                class="mr-[8px]"
                type="info"
                @click="tableController.setTop(scope, !scope.row.isTop)"
                >{{ scope.row.isTop ? "取消置顶" : "置顶" }}</xt-link
              >
              <xt-link
                type="info"
                @click="tableController.setFinish(scope, !scope.row.isFinish)"
                >{{ scope.row.isFinish ? "转待办" : "转完成" }}</xt-link
              >
            </template>
          </xt-table-column>
        </template>
      </xt-table>
    </div>
    <div class="pagination-container mt-[10px] flex flex-row-reverse">
      <xt-pagination
        v-model:current-page="table.pagination.page"
        v-model:page-size="table.pagination.size"
        :total="table.pagination.total"
        @change="tableController.paginationChange"
      />
    </div>

    <job-drawer
      ref="drawer"
      :projectList="projectList"
      @confirm="tableController.getList"
    />

    <!-- 批量操作弹窗 -->
    <todo-batch-dialog
      ref="batchDialog"
      type="job"
      @confirm="drawerController.confirm"
    />
  </div>
</template>

<style lang="scss" scoped>
:deep(.is-set-top) {
  .el-table__cell {
    background-color: rgba(lightblue, 0.4) !important;
  }
}
</style>
